import React, { useEffect, useState } from 'react'
import Taro from '@tarojs/taro';
import { CoverView } from '@tarojs/components'
import styles from './index.module.scss';


// 自定义nav 导航
export default function NavCustomBar(props) {
  const globalData: any = {}
  const { backNode, title, backgroundNav, backgroundBar, top } = props;
  const [navBarHeight, setNavBarHeight] = useState<number>(0); // 顶部导航栏高度
  const [cusNavH, setCusNavH] = useState<number>(0);
  const [statusBarHeight, setStatusBarHeight] = useState<number>(0);

  // 根据不同设备获取height
  const getNavHeight = () => {
    globalData.systeminfo = Taro.getSystemInfoSync();

    if (!globalData.headerBtnPosi)
      globalData.headerBtnPosi = Taro.getMenuButtonBoundingClientRect();
    let newstatusBarHeight = globalData.systeminfo.statusBarHeight; // 状态栏高度
    let headerPosi = globalData.headerBtnPosi; // 胶囊位置信息
    let btnPosi = {
      // 胶囊实际位置，坐标信息不是左上角原点
      height: headerPosi.height,
      width: headerPosi.width,
      top: headerPosi.top - newstatusBarHeight, // 胶囊top - 状态栏高度
      bottom: headerPosi.bottom - headerPosi.height - newstatusBarHeight, // 胶囊bottom - 胶囊height - 状态栏height （胶囊实际bottom 为距离导航栏底部的长度）
      right: globalData.systeminfo.windowWidth - headerPosi.right // 这里不能获取 屏幕宽度，PC端打开小程序会有BUG，要获取窗口高度 - 胶囊right
    };

    const newcusnavH = btnPosi.height + btnPosi.top + btnPosi.bottom; // 导航高度
    const newnavbarHeight = headerPosi.bottom + btnPosi.bottom; // 胶囊bottom + 胶囊实际bottom

    setNavBarHeight(newnavbarHeight);

    setCusNavH(newcusnavH);
    setStatusBarHeight(newstatusBarHeight);
    Taro.setStorageSync('NavBarHeight', newnavbarHeight)
  }

  useEffect(() => {
    getNavHeight();
  }, [])

  return (
    <CoverView className={styles.custom_nav} style={{ height: top ? `${navBarHeight - 10}px` : `${navBarHeight}px`, background: backgroundNav || 'rgb(206, 223, 245)', top: top }}>
      <CoverView
        className={styles.custom_nav_box}
        style={{ height: `${navBarHeight}px`,
        background: backgroundBar || 'rgb(206, 223, 245)',
       }}
      >
        <CoverView
          className={styles.custom_nav_bar}
          style={{
            top: `${statusBarHeight - 1}px`,
            height: `${cusNavH}px`,
            lineHeight: `${cusNavH}px`,
            background: backgroundBar || 'rgb(206, 223, 245)',
          }}
        >

          <CoverView
            className={styles.nav_warp}
            style={{
              height: `${cusNavH}px`,
              lineHeight: `${cusNavH}px`
            }}
          >
            {backNode}
            <CoverView className={styles.title}>{title || '标题'}</CoverView>
          </CoverView>
        </CoverView>
      </CoverView>
    </CoverView>

  )
}
